package org.blade.personal.framework.session.executer;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.blade.personal.framework.dsl.sql.Sql;
import org.blade.personal.framework.jdbc.StatementSetter;
import org.blade.personal.framework.orm.loader.Loader;
import org.blade.personal.framework.orm.loader.concre.EntityLoader;
import org.blade.personal.framework.session.Executer;
import org.blade.personal.framework.session.ResultHandler;

/**
 * 执行器外观
 * @author ZGF
 * @version 0.1
 */
public class ExecuterFacade implements Executer {

	private Sql sql;

	private StatementSetter stmt;

	public ExecuterFacade(StatementSetter stmt) {
		this.stmt = stmt;
	}

	/**
	 * 结果辅助器
	 */
	private ResultHandler resultHandle;

	/**
	 * 查询参数
	 */
	private List<Object> paramaters;

	/**
	 * init executer facade
	 * 
	 * @param stmt 语句
	 * @param sql SQL包装
	 */
	public ExecuterFacade(StatementSetter stmt, Sql sql) {
		this.sql = sql;
		this.stmt = stmt;
		this.resultHandle = sql.getResultHandler();
	}

	@Override
	public Executer append(int index, String value) {

		List<Object> paramaters = getParamatersContainer();
		paramaters.add(index, value);
		return this;
	}

	@Override
	public List<Object> getResultlist() {
		// TODO 赤裸裸的封装需要改进，

		// stmt.setStatement(statement);
//		ResultSet resultSet = stmt.executeQuery(sql.get());
//		System.out.println(sql.get());
		ResultSet resultSet = stmt.executeQuery(sql);
		Loader loader = new EntityLoader(resultHandle);
		List<Object> list = loader.load(resultSet, resultHandle);
		return list;
	}

	private List<Object> getParamatersContainer() {

		if (null == paramaters || paramaters.size() == 0) {
			paramaters = new ArrayList<Object>();
		}
		return paramaters;
	}

	@Override
	public Executer append(int index, Integer value) {

		List<Object> paramaters = getParamatersContainer();
		paramaters.add(index, value);
		return this;
	}

	@Override
	public Executer append(int index, Double value) {

		List<Object> paramaters = getParamatersContainer();
		paramaters.add(index, value);
		return this;
	}

	@Override
	public Executer append(int index, Float value) {

		List<Object> paramaters = getParamatersContainer();
		paramaters.add(index, value);
		return this;
	}

	@Override
	public Executer append(int index, Byte value) {

		List<Object> paramaters = getParamatersContainer();
		paramaters.add(index, value);
		return this;
	}

	@Override
	public Executer append(int index, Long value) {

		List<Object> paramaters = getParamatersContainer();
		paramaters.add(index, value);
		return this;
	}

	@Override
	public Executer append(Object[] values) {

		List<Object> paramaters = getParamatersContainer();

		for (Object value : values) {
			paramaters.add(value);
		}
		return this;
	}

}
